package com.hex.liyue.usermodule.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hex.liyue.R;
import com.hex.liyue.commonmodule.activity.BaseActivity;
import com.hex.liyue.commonmodule.glide.GlideCircleTransform;
import com.hex.liyue.commonmodule.glide.GlideRoundTransform;
import com.hex.liyue.commonmodule.utils.DateUtils;
import com.hex.liyue.commonmodule.utils.FileUtis;
import com.hex.liyue.commonmodule.utils.ImageUtils;
import com.hex.liyue.commonmodule.utils.SexUtils;
import com.hex.liyue.commonmodule.utils.StatusBarCompatUtils;
import com.hex.liyue.commonmodule.utils.T;
import com.hex.liyue.commonmodule.view.picker.OptionPicker;
import com.hex.liyue.usermodule.bean.MyMessageResultBean;
import com.hex.liyue.usermodule.presenter.IPersonEditView;
import com.hex.liyue.usermodule.presenter.PersonEditPresenter;
import com.hex.liyue.usermodule.view.DatePicker;
import com.hex.liyue.usermodule.view.PhotoSelectDialog;
import com.hex.liyue.usermodule.view.PopSex;
import com.hex.liyue.usermodule.view.PopStarSign;

import java.io.File;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 这是一个个人信息编辑的页面
 * Created by yukoyuan on 16/6/17.
 */
public class PersonEditActivity extends BaseActivity implements IPersonEditView {
    @Bind(R.id.iv_toobar_back)
    ImageView ivToobarBack;
    @Bind(R.id.tv_toobar_title)
    TextView tvToobarTitle;
    @Bind(R.id.tv_toobar_right)
    TextView tvToobarRight;

    @Bind(R.id.iv_person_edit_avator)
    ImageView ivPersonEditAvator;
    @Bind(R.id.et_person_edit_name)
    EditText etPersonEditName;
    @Bind(R.id.tv_person_edit_sex)
    TextView tvPersonEditSex;
    @Bind(R.id.tv_person_edit_birthday)
    TextView tvPersonEditBirthday;
    @Bind(R.id.tv_person_edit_zodiac)
    TextView tvPersonEditZodiac;
    @Bind(R.id.tv_person_edit_autograph)
    TextView tvPersonEditAutograph;
    @Bind(R.id.tv_person_edit_photo_num)
    TextView tvPersonEditPhotoNum;
    @Bind(R.id.v_pop)
    View vPop;

    public static String signature;

    private PhotoSelectDialog photoSelectDialog;//头像对话框
    private PopSex popSex;//性别对话框
    private PopStarSign popStarSign;//星座对话框
    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 裁剪结果
    private static final int REQUEST_SIGNATURE = 4;// 个性签名
    private static final int REQUEST_MYPHOTO = 5;// 我的照片
    private PersonEditPresenter personEditPresenter;
    private boolean isAvater = false;//有没有头像

    public static boolean falg = false;
    private File photoFile;
    private File avatorfile;


    @Override
    protected void bindPresenter() {
        personEditPresenter = new PersonEditPresenter(this);
    }

    @Override
    protected void initData(Bundle extras) {
        personEditPresenter.getMyMessage();
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_person_edit;
    }

    @Override
    protected void initToolbar() {
        StatusBarCompatUtils.compat(this);
        ivToobarBack.setVisibility(View.VISIBLE);
        tvToobarTitle.setVisibility(View.VISIBLE);
        tvToobarTitle.setText("个人信息");
        tvToobarRight.setVisibility(View.VISIBLE);
        tvToobarRight.setText("保存");
    }


    @OnClick({
            R.id.iv_toobar_back,
            R.id.tv_toobar_right,
            R.id.rl_person_edit_avator,
            R.id.rl_person_edit_sex,
            R.id.rl_person_edit_birthday,
            R.id.rl_person_edit_zodiac,
            R.id.rl_signature,
            R.id.rl_person_edit_photos,
            R.id.rl_person_edit_video
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_toobar_back://返回
                onBackPressed();
                break;
            case R.id.tv_toobar_right://保存
                if (etPersonEditName.getText().toString().length() > 15) {
                    T.show(this, "昵称字数不能超过15字", 0);
                } else {
                    personEditPresenter.updateMyMessage();
                }
                break;
            case R.id.rl_person_edit_avator://头像
                showPhotoDialog();
                break;
            case R.id.rl_person_edit_sex://性别
                showDialogSex();
                break;
            case R.id.rl_person_edit_birthday://日期
                showBirthdayDate();
                break;
            case R.id.rl_person_edit_zodiac://星座
                showStarSign();
                break;
            case R.id.rl_person_edit_photos://我的照片
                startMyPhotoActivity();
                break;
            case R.id.rl_signature://个新签名
                startNewSignatureActivity();
                break;
            case R.id.rl_person_edit_video://我的视频
                startVideoListsActivity();
                break;
        }
    }

    /**
     * 我的是视频界面
     */
    private void startVideoListsActivity() {
        Intent intent = new Intent(PersonEditActivity.this, VideoListActivity.class);
        startActivity(intent);
    }

    /**
     * 打开我的照片编辑
     */
    public void startMyPhotoActivity() {
        Intent intent = new Intent(PersonEditActivity.this, MyPhotoActivity.class);
        startActivityForResult(intent, REQUEST_MYPHOTO);
    }

    /**
     * 编辑我的个性签名
     */
    public void startNewSignatureActivity() {
        Intent intent = new Intent(PersonEditActivity.this, NewSignatureActivity.class);
        intent.putExtra("signature", getSignature());
        startActivityForResult(intent, REQUEST_SIGNATURE);
    }


    /**
     * 启动裁剪图片功能
     *
     * @param uri
     * @param size
     */
    private void startPhotoZoom(Uri uri, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 4);
        intent.putExtra("aspectY", 3);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }


    /**
     * Activity回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST_TAKEPHOTO && resultCode == RESULT_OK) {
            startPhotoZoom(Uri.fromFile(photoFile), 150);
        } else if (requestCode == PHOTO_REQUEST_GALLERY && resultCode == RESULT_OK) {
            if (data != null) {
                startPhotoZoom(data.getData(), 150);
            }
        } else if (requestCode == PHOTO_REQUEST_CUT && resultCode == RESULT_OK) {
            if (data != null) {
                setPicToView(data);
            }
        } else if (requestCode == REQUEST_SIGNATURE && resultCode == RESULT_OK) {
            tvPersonEditAutograph.setText(signature);
        } else if (requestCode == REQUEST_MYPHOTO && resultCode == RESULT_OK) {
        }

    }

    /**
     * 获得截取后的照片
     *
     * @param data
     */
    private void setPicToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            File file = ImageUtils.saveBitmapFile(photo);
            if (extras != null) {
                Glide.with(this)
                        .load(file)
                        .error(R.drawable.icon_no_thing)
                        .transform(new GlideRoundTransform(this))
                        .into(ivPersonEditAvator);
                avatorfile = file;
            }
        }

    }

    /**
     * 选择星座的对话框
     */
    private void showStarSign() {
        OptionPicker edupicker = new OptionPicker(this, new String[]{
                "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "魔蝎座", "射手座", "水瓶座", "双鱼座"
        });
        edupicker.setOffset(2);
        edupicker.setSelectedIndex(0);
        edupicker.setTextSize(12);
        edupicker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(String option) {
                tvPersonEditZodiac.setText(option);
            }
        });
        edupicker.show();
    }

    /**
     * 选择生日的对话框
     */
    private void showBirthdayDate() {
        DatePicker birtydaypicker = new DatePicker(this);
        int NowYear = DateUtils.getNowYear();
        birtydaypicker.setRange(1975, NowYear);//年份范围
        birtydaypicker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                tvPersonEditBirthday.setText(year + "-" + month + "-" + day);
            }
        });
        birtydaypicker.show();
    }

    /**
     * 选择性别的对话框
     */
    private void showDialogSex() {
        OptionPicker picker = new OptionPicker(this, new String[]{
                "男", "女"
        });
        picker.setOffset(2);
        picker.setSelectedIndex(1);
        picker.setTextSize(11);
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(String option) {
                tvPersonEditSex.setText(option);
            }
        });
        picker.show();
    }

    /**
     * 显示头像对话框
     */
    private void showPhotoDialog() {
        if (photoSelectDialog == null) {
            photoSelectDialog = new PhotoSelectDialog(this);
            photoSelectDialog.setOnPhotoListener(new PhotoSelectDialog.OnPhotoListener() {
                @Override
                public void photo() {
                    Intent intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            "image/*");
                    startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                }

                @Override
                public void camera() {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    String cameraPath = "/liyue/userphoto.jpg";
                    FileUtis.createDir();
                    photoFile = new File(Environment.getExternalStorageDirectory(), cameraPath);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
                }

                @Override
                public void cancel() {
                    photoSelectDialog.dismiss();
                }
            });
        }
        photoSelectDialog.show();
    }

    @Override
    public File getAvatar() {
        return avatorfile;
    }

    @Override
    public boolean getIsAvater() {
        return isAvater;
    }

    @Override
    public String getNickname() {
        return etPersonEditName.getText().toString();
    }

    @Override
    public long getBirthday() {
        return DateUtils.getDateLongTime("yyyy-MM-dd", tvPersonEditBirthday.getText().toString()) / 1000;
    }

    @Override
    public String getStarSign() {
        return tvPersonEditZodiac.getText().toString();
    }

    @Override
    public String getSignature() {
        return tvPersonEditAutograph.getText().toString();
    }

    @Override
    public int getSex() {
        String sex = tvPersonEditSex.getText().toString();
        return SexUtils.getIntSex(sex);
    }


    @Override
    public void setMyMessage(MyMessageResultBean personEditPersenterBean) {
        Glide.with(this)
                .load(personEditPersenterBean.data.avatar)
                .error(R.drawable.icon_no_thing)
                .transform(new GlideCircleTransform(this))
                .into(ivPersonEditAvator);
        if (!TextUtils.isEmpty(personEditPersenterBean.data.avatar)) {
            isAvater = true;
        } else {
            isAvater = false;
        }
        etPersonEditName.setText(personEditPersenterBean.data.nickname);
        tvPersonEditSex.setText(SexUtils.getSex(personEditPersenterBean.data.sex));
        tvPersonEditBirthday.setText(DateUtils.getFormatDate(personEditPersenterBean.data.birthday * 1000, "yyyy-MM-dd"));
        tvPersonEditZodiac.setText(personEditPersenterBean.data.star_sign);//星座
        tvPersonEditAutograph.setText(personEditPersenterBean.data.signature);//签名
        if (personEditPersenterBean.data.urls != null) {
            tvPersonEditPhotoNum.setText(personEditPersenterBean.data.urls.size() + "张");
        }
    }

    @Override
    public void closeAtivity() {
        onBackPressed();
    }

    @Override
    public void showLod(String msg) {
        showLoad(PersonEditActivity.this, msg);
    }

    @Override
    public void closeLod() {
        closeLoad();
    }

    @Override
    public void showT(String msg) {
        showToast(PersonEditActivity.this, msg);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (falg) {
            personEditPresenter.getMyMessage();
        }
    }
}
